//
//  LJHAlbumsDetailViewController.m
//  HEARME
//
//  Created by liujinhui on 16/1/27.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "LJHAlbumsDetailViewController.h"
#import "LJHAlbumModel.h"
#import "LJHAlbumHeadView.h"
#import "FXBlurView.h"
#import "UIScrollView+MJRefresh.h"
#import "MJRefresh.h"
#import "LJHAlbumsDetailCell.h"
#import "LJHPlayerViewController.h"
@interface LJHAlbumsDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property(nonatomic,retain)UITableView *albumTableView;
@property(nonatomic,retain)NSMutableArray *allTrackArray;
@property(nonatomic,retain)LJHAlbumModel *myAlbum;
@property(nonatomic,retain)LJHAlbumHeadView *tableHeadView;
@property(nonatomic,assign)CGFloat cellHeight;
@property(nonatomic,assign)NSInteger currentPage;
@property(nonatomic,retain)UIImageView *backgroundImageView;
@property(nonatomic,retain)UIImageView *overImage;
@property(nonatomic,retain)FXBlurView *blurView;

//@property(nonatomic,retain)UIButton *nextBtn;


@end

@implementation LJHAlbumsDetailViewController
-(void)dealloc
{
    [_blurView release];
    [_backgroundImageView release];
    [_myTitle release];
    [_tableHeadView release];
    [_allTrackArray release];
    [_albumTableView release];
    [_myAlbum release];
    [_albumId release];
    [super dealloc];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[LJHPlayBtn shareButton].musicBtn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getData];
    
    if ([LJHPlayerViewController sharaMusicPlayer].player.state == STKAudioPlayerStatePlaying) {
        
        [[LJHPlayBtn shareButton] startCircle];
    }
    if ([LJHPlayerViewController sharaMusicPlayer].player.state == STKAudioPlayerStatePaused) {
        
        [[LJHPlayBtn shareButton] stopCircle];
        
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [GiFHUD setGifWithImageName:@"loading.gif"];
    [GiFHUD show];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"专辑详情";
    
    
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0 , 20, 30);
    backButton.backgroundColor = [UIColor clearColor];
    [backButton setImage:[UIImage imageNamed:@"btn_back_n@2x.png"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_back_h@2x.png"] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationController.navigationBar.translucent = YES;
    //初始化数组
    self.allTrackArray = [NSMutableArray array];
    [self createSubviews];
    self.currentPage = 1;
    
}




#pragma mark - 请求数据
-(void)getData
{
    
    NSString *urlStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/20?position=2&albumId=%@&isAsc=true&device=iphone&title=%@&pageSize=20",self.albumId,self.currentPage,self.albumId , self.myTitle];
    NSLog(@"9999999%@ %ld %@",self.albumId,(long)self.currentPage,self.myTitle);
    [LJHAppTools afnGetRequest:urlStr block:^(id result) {
        
        self.myAlbum = [LJHAlbumModel modelWithDictionary:[result objectForKey:@"album"]];
        
        self.myAlbum.myId = self.albumId;
        self.myAlbum.albumCoverUrl290 = [[result objectForKey:@"album"] objectForKey:@"coverSmall"];
        self.myAlbum.tracksCounts = [[result objectForKey:@"album"] objectForKey:@"tracks"];
        
        self.myAlbum.isFavor = NO;
        
        
        if ([[[LJHFMData shareFMDB] selectAlbumIdData] containsObject:self.myAlbum.myId]) {
            self.myAlbum.isFavor = YES;
        }
        
        NSLog(@"2222222%@",self.myAlbum.albumPic);
        
        if (self.myAlbum.isFavor) {
            [self.tableHeadView.favorBtn setImage:[UIImage imageNamed:@"find_album_fav_n"] forState:UIControlStateNormal];
            
        }
        else
        {
            [self.tableHeadView.favorBtn setImage:[UIImage imageNamed:@"find_album_unfav_n"] forState:UIControlStateNormal];
        }
        
        [self.tableHeadView.favorBtn addTarget:self action:@selector(favorAction:) forControlEvents:UIControlEventTouchUpInside];
        
        self.navigationItem.title = self.myAlbum.title;
        
        NSURL *urlBg = [NSURL URLWithString:self.myAlbum.coverLarge];
        
        [self.backgroundImageView sd_setImageWithURL:urlBg placeholderImage:[UIImage imageNamed:@"1024.jpg"]];
        NSURL *url = [NSURL URLWithString:self.myAlbum.coverSmall];
        [self.tableHeadView.albumPic sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1024.jpg"]];
        self.tableHeadView.authorName.text = self.myAlbum.nickname;
        self.tableHeadView.albumDigest.text = self.myAlbum.intro;
        self.tableHeadView.playCount.text = [NSString stringWithFormat:@"%ld",self.myAlbum.playtimes];
        NSURL *urlImg = [NSURL URLWithString:self.myAlbum.avatarPath];
        [self.tableHeadView.avatarBtn sd_setBackgroundImageWithURL:urlImg forState:UIControlStateNormal placeholderImage:PLACEHOLDER];
        
        NSMutableDictionary *trackDic = [result objectForKey:@"tracks"];
        
        for (NSMutableDictionary *dic in [trackDic objectForKey:@"list"]) {
            
             LJHTrackModel *model = [LJHTrackModel modelWithDictionary:dic];
            [self.allTrackArray addObject:model];
            
        }
        
        [self.albumTableView reloadData];
        
        self.currentPage ++;
        [self.albumTableView.footer endRefreshing];
        
    } error:^(NSError *error) {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"您的设备无网络访问" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
        
        UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertC addAction:cancelButton];
    }];
}

#pragma mark - 创建子视图
-(void)createSubviews
{
    
    //背景
    self.backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT*0.4)];
    self.backgroundImageView.backgroundColor = [UIColor clearColor];
    self.backgroundImageView.alpha = 0.5;
    [self.view addSubview:self.backgroundImageView];
    [_backgroundImageView release];
    
    
    _blurView = [[FXBlurView alloc]initWithFrame:self.backgroundImageView.bounds];
    [_backgroundImageView addSubview:_blurView];
    _blurView.blurRadius = 100;
    [_blurView release];
    
    self.overImage = [[UIImageView alloc] initWithFrame:self.backgroundImageView.frame];
    self.overImage.image = [UIImage imageNamed:@"header_over@2x.png"];
    [self.backgroundImageView addSubview:self.overImage];
    [_overImage release];
    
    
    
    self.albumTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT-64) style:UITableViewStylePlain];
    self.albumTableView.backgroundColor = [UIColor clearColor];
    [_albumTableView release];
    self.albumTableView.dataSource = self;
    self.albumTableView.delegate = self;
    [self.albumTableView registerClass:[LJHAlbumsDetailCell class] forCellReuseIdentifier:@"cell"];
//    [self.albumTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"c"];
    [self.albumTableView reloadData];
    UIView *footerView = [[UIView alloc] init];
    self.albumTableView.tableFooterView = footerView;
    [self.view addSubview:self.albumTableView];
    [footerView release];
    
    [LJHPlayBtn shareButton].frame =CGRectMake(WIDTH*0.4, HEIGHT-WIDTH*0.2, WIDTH*0.2, HEIGHT*0.2);
    [self.view addSubview :[LJHPlayBtn shareButton]];
    
    
    self.tableHeadView = [[LJHAlbumHeadView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT*0.25)];
    self.tableHeadView.backgroundColor = [UIColor clearColor];
    self.albumTableView.tableHeaderView = self.tableHeadView;
    
    
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    self.albumTableView.footer = footer;
    
}

#pragma mark - playButton
-(void)buttonAction:(UIButton *)btn
{
    
    
    LJHPlayerViewController *player = [LJHPlayerViewController sharaMusicPlayer];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:player];
    
    [self.view.window.rootViewController presentViewController:naVC animated:YES completion:^{
        
    }];
    
    
}


#pragma mark - 返回按钮方法
-(void)backButtonAction:(UIButton *)btn
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - tableView协议方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.allTrackArray.count;

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LJHAlbumsDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    LJHTrackModel *model = [self.allTrackArray objectAtIndex:indexPath.row];
    
    cell.trackModel = model;
//    NSLog(@"rrrr%@",cell.trackModel.title);
    self.cellHeight = cell.playCount.frame.origin.y + cell.playCount.frame.size.height + 10;
        
    return cell;
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.cellHeight;
//    return 100;
    
}

#pragma mark section头视图

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    LJHBaseView *headView = [[[LJHBaseView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 30)] autorelease];
    
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(headView.frame.origin.x + 20, headView.frame.origin.y+10, 100, headView.frame.size.height - 10)];
    myLabel.backgroundColor = [UIColor clearColor];
    myLabel.text = [NSString stringWithFormat:@"共 %ld 集", (long)self.myAlbum.tracks];
    [myLabel sizeToFit];
    [headView addSubview:myLabel];
    [myLabel release];
    
    
    
    UIButton *sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sortButton.frame = CGRectMake(headView.frame.size.width -60, headView.frame.origin.y+10 , 30, headView.frame.size.height - 10);
    sortButton.backgroundColor = [UIColor clearColor];
    [sortButton setTitle:@"排序" forState:UIControlStateNormal];
    sortButton.titleLabel.font = [UIFont systemFontOfSize:13 weight:0];
    [sortButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sortButton addTarget:self action:@selector(sortAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:sortButton];
    
    
    return headView;
}
#pragma mark - 排序方法(倒序)
-(void)sortAction:(UIButton *)btn
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:_allTrackArray];
    self.allTrackArray = [NSMutableArray array];
    for (NSInteger i = array.count-1; i>=0; i--) {
        [self.allTrackArray addObject:[array objectAtIndex:i]];
    }
    
    //    NSLog(@"%@", self.allTrackArray);
    [self.albumTableView reloadData];
    
}

#pragma mark tableView点击方法

#pragma mark - 播放音乐跳转到播放页面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    LJHPlayerViewController *player =[LJHPlayerViewController sharaMusicPlayer];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:player];
    LJHTrackModel *sing = [self.allTrackArray objectAtIndex:indexPath.row];
    player.song_id = sing.trackId;
    player.allMusicArray = self.allTrackArray;
    player.indexRow = indexPath.row;
    [self presentViewController:naVC animated:YES completion:^{
        
    }];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return HEIGHT*0.06;
}

#pragma mark - scrollView协议方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView.contentOffset.y < 0) {
        
        self.backgroundImageView.frame = CGRectMake(0, 0, WIDTH, HEIGHT*0.4-scrollView.contentOffset.y);
        self.blurView.frame = self.backgroundImageView.bounds;
        self.blurView.blurRadius = 1;
        self.overImage.frame = self.backgroundImageView.bounds;
    }
    if (scrollView.contentOffset.y > 0) {
        
        self.backgroundImageView.frame = CGRectMake(0, -scrollView.contentOffset.y, WIDTH, HEIGHT*0.4);
        
    }
    
    if (scrollView.contentOffset.y == 0) {
        self.blurView.blurRadius = 100;
    }
    
    [self.view bringSubviewToFront:self.albumTableView];
    [self.view bringSubviewToFront:[LJHPlayBtn shareButton]];
    
}

#pragma mark - 收藏按钮

-(void)favorAction:(UIButton *)btn
{
    if (_myAlbum.isFavor) {
        [[LJHFMData shareFMDB] deleteByAlbumId:self.myAlbum.myId];
        [self.tableHeadView.favorBtn setImage:[UIImage imageNamed:@"find_album_unfav_n"] forState:UIControlStateNormal];
        self.myAlbum.isFavor = NO;
    }
    else{
        [[LJHFMData shareFMDB] insertAlbumData:self.myAlbum];
        [self.tableHeadView.favorBtn setImage:[UIImage imageNamed:@"find_album_fav_n"] forState:UIControlStateNormal];
        self.myAlbum.isFavor = YES;
    }
}

//-(void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    [self removeFromParentViewController];
//    [self.view removeFromSuperview];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
